<template>
	<div class="content-page">
		<div class="content-nav">
			<el-breadcrumb class="breadcrumb" separator="/">
				<el-breadcrumb-item :to="{ name: 'dashboard' }">首页</el-breadcrumb-item>
				<el-breadcrumb-item>视频管理</el-breadcrumb-item>
				<el-breadcrumb-item>{{infoForm.id ? '编辑视频' : '上传视频'}}</el-breadcrumb-item>
			</el-breadcrumb>
			<div class="operation-nav">
				<el-button type="primary" @click="goBackPage" icon="arrow-left">返回列表</el-button>
			</div>
		</div>
		<div class="content-main">
			<div class="form-table-box">
				<el-form ref="infoForm" :rules="infoRules" :model="infoForm" label-width="120px">
					<el-form-item label="视频名称" prop="videoName">
						<el-input v-model="infoForm.videoName"></el-input>
					</el-form-item>
					<el-form-item label="所属分类" prop="categoryId">
						<el-select v-model="infoForm.categoryId" placeholder="请选择分类">
							<el-option :label="item.category" :value="item.categoryId" v-for="(item,index) in categoryList"></el-option>
						</el-select>
					</el-form-item>
					<el-form-item label="封面" prop="showImage">
						<div class="flex align-items">
							<div v-if="infoForm.showImage" class="pos-r">
								<el-image :src="infoForm.showImage" class="image-show" style="width: 165px;height: 105px;" />
								<i class="el-icon-error pos-a delBtn" @click="delBtnFun"></i>
							</div>
							<el-upload class="image-uploader" name="upfile" :action="imgServer" :on-success="handleUploadImageSuccess"
							 :limit="1" :on-progress="uploadingImgAction" :on-remove="handleRemove" :before-upload="beforeUpload" v-else>
								<i class="el-icon-plus image-uploader-icon"></i>
								<div slot="tip" class="el-upload__tip">{{uploadingImgStatus?'压缩中...请稍等':'图片尺寸:678*380 大小限制:2M以内'}}</div>
							</el-upload>

						</div>
					</el-form-item>
					<el-form-item label="封面显示">
						<el-radio-group v-model="infoForm.showMode">
							<el-radio :label="2" name="type">大图</el-radio>
							<el-radio :label="1" name="type">小图</el-radio>
							<el-radio :label="0" name="type">无图</el-radio>
						</el-radio-group>
					</el-form-item>
					<el-form-item label="视频文件">
						<div class="upload-demo">
							<div class="el-upload el-upload--text txt-l" @click="handleClick" @keydown="handleKeydown">
								<el-button slot="trigger" size="small" type="primary" class="el-button el-button--primary el-button--small">选取文件</el-button>
								<input type="file" name="file" class="el-upload__input" ref="input" @change="handleChange" />
								<div slot="tip" class="el-upload__tip">上传视频请提前压缩</div>
							</div>
						</div>
						<div style="width: 618px;height: 350px;" v-if="infoForm.videoUrl">
							<video-player class="video-player vjs-custom-skin" ref="videoPlayer" :playsinline="true" :options="video_Config"></video-player>
						</div>
					</el-form-item>
					<el-form-item label="视频简介" prop="simple_desc">
						<div class="ueditor-wrap">
							<vue-ueditor-wrap v-model="msg" :config="ueditorConfig.config" @ready="ueditorConfig.ready"></vue-ueditor-wrap>
						</div>
						<div class="form-tip"></div>
					</el-form-item>
					<el-form-item label="显示状态">
						<el-radio-group v-model="infoForm.showVideoMode">
							<el-radio :label="1" name="type">显示</el-radio>
							<el-radio :label="0" name="type">隐藏</el-radio>
						</el-radio-group>
					</el-form-item>
					<el-form-item label="是否推荐">
						<el-radio-group v-model="infoForm.recommendFlag">
							<el-radio :label="1" name="type">是</el-radio>
							<el-radio :label="0" name="type">否</el-radio>
						</el-radio-group>
					</el-form-item>
					<el-form-item label="排序">
						<el-input-number v-model="infoForm.sorting" :min="0"></el-input-number>
					</el-form-item>
					<el-form-item>
						<el-button type="primary" @click="onSubmitInfo">确定保存</el-button>
						<el-button @click="goBackPage">取消</el-button>
					</el-form-item>
				</el-form>
			</div>
		</div>
		<el-dialog title="视频模块" :visible.sync="dialogVisible" width="30%" :show-close="false" :closeOnClickModal="false">
			<div class="progressContent">
				<el-progress :percentage="videoPercentage" v-if="!change_video_status"></el-progress>
				<div v-if="!change_video_status" class="mt10">文件上传中</div>
				<div v-else class="mt10">服务器转码中...</div>
				<div class="mt10">请耐心等待</div>
			</div>
			<div slot="footer" class="dialog-footer">
				<el-button @click="close">取 消</el-button>
			</div>
		</el-dialog>
	</div>
</template>

<script>
	import {
		getCategoryList,
		addVideo,
		getVideoToken,
		setVideoPfop,
		getVideoPfopStatus,
		getVideoInfo
	} from '@/api/permission'
	import ueditorConfig from '@/config/ueditorConfig'
	import config from '@/config/baseUrl'
	import uploadFun from '@/assets/js/qiniu'
	import videoConfig from '@/assets/js/videoConfig'
	export default {
		data() {
			return {
				categoryList: [],
				ueditorConfig: ueditorConfig,
				imgServer: `${config.baseUrl}/vms/v1/image/upload`,
				videoServer: `${config.baseUrl}/vms/v1/video/upload`,
				uploadingImgStatus: false,
				srcList: [],
				msg: '', //富文本
				infoForm: {
					id: '',
					videoName: "",
					categoryId: "",
					category: "",
					showMode: 2,
					showVideoMode: 1,
					showImage: null,
					videoDesc: null, //短视频文件
					videoUrl: null,
					sorting: null,
					recommendFlag: 0
				},
				infoRules: {
					videoName: [{
						required: true,
						message: '请输入名称',
						trigger: 'blur'
					}],
					categoryId: [{
						required: true,
						message: '请选择分类',
						trigger: 'change'
					}],
					showImage: [{
						required: true,
						message: '请上传封面',
						trigger: 'change'
					}, ],
				},
				videoPercentage: 0,
				uploading_video: false, //新增部分
				change_video_status: false,
				video_Config: videoConfig,
				show_video: true,
				timer: null,
				dialogVisible: false
			}
		},
		methods: {
			uploadingImgAction(event, file, fileList) {
				let percentage = parseInt(event.loaded / event.total * 100)
				if (percentage == 100) {
					this.uploadingImgStatus = true
				}
			},
			handleRemove() {
				this.infoForm.showImage = ''
			},
			goBackPage() {
				this.$router.push({
					name: 'goods'
				})
			},
			delBtnFun() {
				this.infoForm.showImage = ''
			},
			beforeUpload(file) {
				console.log(2222)
				let self = this
				if ((file.size / (1024 * 1024)) > 2) {
					self.$notify({
						title: '提示',
						message: '文件太大2M以内'
					})
					return false
				}
			},
			onSubmitInfo() {
				let self = this
				self.$refs['infoForm'].validate((valid) => {
					if (valid) {
						self.infoForm.videoDesc = self.msg
						addVideo(self.infoForm).then((res) => {
							self.$message({
								message: '视频保存成功',
								type: 'success'
							});
							if (self.infoForm.id) {
								self.$router.push({
									name: 'goods'
								})
							}
						}).catch(err => {
							console.log(err)
						})
					} else {
						return false;
					}
				});
			},
			handleUploadImageSuccess(res, file) {
				this.uploadingImgStatus = false
				if (res.respCode.code == "EDI-10000") {
					this.infoForm.showImage = res.data.fileUrl
					this.srcList = [res.data.fileUrl]
				}
			},
			getInfo(id) {
				console.log(id, 9999)
				// let data = JSON.parse(self.$route.params.data)

				//加载商品详情
				let self = this
				getVideoInfo({
					id: id
				}).then((res) => {
					for (let key in self.infoForm) {
						if (key == 'videoDesc') {
							self.msg = res[key]
						}
						self.video_Config[`sources`][0].src = res.videoUrl
						self.infoForm[key] = res[key]
					}
				})
			},
			getCategoryListFun() {
				let self = this
				getCategoryList({
					index: 0,
					size: 99
				}).then(res => {
					self.categoryList = res.content
				})
			},
			//文件
			handleClick() {
				this.$refs.input.value = ''
				this.$refs.input.click();
			},
			handleChange(ev) {
				const files = ev.target.files;
				if (!files) return;
				this.uploadFiles(files);
			},
			uploadFiles(files) {
				let self = this
				let observer = {
					next(res) {
						self.videoPercentage = parseInt(res.total.percent)
					},
					error(err) {
						// ...
					},
					complete(res) {
						console.log("完成==》", res)
						if (res.key) {
							setVideoPfop({
								key: res.key
							}).then(res => {
								console.log(res)
								self.change_video_status = true
								self.timer = setInterval(() => {
									getVideoPfopStatus({
										id: res.persistentId
									}).then(res => {
										if (res[0].status.code == 0) {
											clearInterval(self.timer)
											self.dialogVisible = false
											self.change_video_status = false
											self.video_Config[`sources`][0].src = res[0].url
											self.infoForm.videoUrl = res[0].url
										}
									})
								}, 1000)
							})
						}
					}
				}
				self.dialogVisible = true
				self.subscription = uploadFun(self.$store.state.videoToken, files[0], observer)
			},
			close() {
				let self = this
				self.change_video_show = false
				self.dialogVisible = false
				self.change_video_status = false
				if (self.subscription) {
					self.subscription.unsubscribe()
				}
				clearInterval(self.timer);
			},
			beforeDestroy() {
				clearInterval(self.timer);
			},
			handleKeydown(e) {
				if (e.target !== e.currentTarget) return;
				if (e.keyCode === 13 || e.keyCode === 32) {
					this.handleClick();
				}
			}
		},
		components: {},
		mounted() {
			let self = this
			if (self.$route.query.id) {
				self.getInfo(self.$route.query.id)
			}
			clearInterval(self.timer);
			if (!self.$store.state.videoToken) {
				getVideoToken().then(res => {
					self.$store.commit('SET_VIDEOTOKEN', res.token)
				})
			}
			this.getCategoryListFun()
		}
	}
</script>

<style>
	.image-uploader {
		min-height: 105px;
		height: auto !important;
	}

	.image-uploader .el-upload {
		border: 1px solid #d9d9d9;
		cursor: pointer;
		position: relative;
		overflow: hidden;
	}

	.image-uploader .el-upload:hover {
		border-color: #20a0ff;
	}

	.image-uploader .image-uploader-icon {
		font-size: 28px;
		color: #8c939d;
		width: 187px;
		height: 105px;
		line-height: 105px;
		text-align: center;
	}

	.image-show {
		width: 187px;
		height: 105px;
		display: block;
	}

	.image-uploader.new-image-uploader {
		font-size: 28px;
		color: #8c939d;
		width: 165px;
		height: 105px;
		line-height: 105px;
		text-align: center;
	}

	.image-uploader.new-image-uploader .image-uploader-icon {
		font-size: 28px;
		color: #8c939d;
		width: 165px;
		height: 105px;
		line-height: 105px;
		text-align: center;
	}

	.delBtn {
		position: absolute;
		font-size: 24px;
		right: -12px;
		top: -12px;
		color: #FF5D6A;
		cursor: pointer;
		z-index: 999;
	}
</style>
